
package springair.business.delegates.tree 
{
	import org.as3commons.lang.ClassUtils;
	import org.as3commons.reflect.Type;
	/**
	 * @author a.fell
	 */
	public class BuildObjectTreeDelegate 
	{
		
		
		public function buildTreeFromTypeList(list:Array):*
		{
			var root:XML = <items/>;
			
			clearNodeList();
			
			var item:Type;
			var fullPackage:String;
			var packageAtoms:Array;
			
			var i:int = list.length;
			while(i--)
			{
				item = list[i];
				
				fullPackage = item.fullName.replace(classNameExpression, "");
				
				packageAtoms = fullPackage.split(".");
				
				var nodeName:String;
				var parent:XML = root;
				var node:XML;
				
				if(packageAtoms.length > 1)
				{
					for (var j : int = 0; j < packageAtoms.length; j++) 
					{
						nodeName = packageAtoms[j];
						
						node = getNodeWithName(nodeName, parent);
						parent = node;
					}
				}
				node = <node/>;
				node.@label = item.name;
				node.@alias = item.fullName;
				
				node.@type = ClassUtils.isInterface(item.clazz) ? "interface" : "class";
				
				parent.appendChild(node);
			}
			
			clearNodeList();
			
			return root.children();
		}
		
		
		
		private function getNodeWithName(nodeName:String, parent:XML):XML
		{
			var node:* = nodeList[nodeName];
			
			if(!node)
			{
				node = nodeList[nodeName] = <node/>;
				node.@label = nodeName;
				node.@type = "package";
				parent.appendChild(node);
			}
			
			return node;
		}

		
		
		private function clearNodeList():void
		{
			nodeList.length = 0;
		}

		
		
		private var nodeList:Array = [];
		
		
		private var classNameExpression:RegExp = /::\w+/;
		
	}
}
